import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/ute/uteped_config.dart';
import 'package:share_fit/app/ute/uteped_const.dart';

import 'permission_const.dart';
import 'permission_state.dart';

class PermissionLogic extends BaseController {
  static const authedPackages = "authedPackages";
  final PermissionState state = PermissionState();

  @override
  void onResumed() {
    super.onResumed();
    delayed(
        () => {
              UTEPedConfig.instance.checkNotificationEnable(),
              if (state.permissionList.isNotEmpty)
                {queryPermissions(state.permissionList)},
            },
        milliseconds: 50);
  }

  void queryPermissions(List permissionList) {
    List<String> permissions = [];
    for (var permissionItem in permissionList) {
      permissions.add(permissionItem["permission"]);
    }

    dRemoteReqAsync(PermissionConst.methodQueryPermissions, {UTEPedConst.typeList: permissions})
        .then((result) => _onQueryPermissions(permissionList, result));
  }

  void _onQueryPermissions(List permissionList, result) {
    if (state.permissionList.isEmpty) {
      state.permissionList.addAll(permissionList);
    }
    state.authedPermissions = result;
    state.authedItems.clear();
    state.notAuthItems.clear();
    for (var permissionItem in permissionList) {
      if (hasPermission(permissionItem[PermissionConst.keyPermission])) {
        state.authedItems.add(permissionItem);
      }
      else {
        state.notAuthItems.add(permissionItem);
      }
    }

    update(["list_container"]);
  }

  bool hasPermission(String permission) {
    if (state.authedPermissions.containsKey(permission)) {
      return state.authedPermissions[permission]!;
    }

    return false;
  }

  void toPermissionPage(type, permission) {
    dRemoteReqAsync(PermissionConst.methodToPermissionPage, {UTEPedConst.keyType: type, UTEPedConst.keyPermission: permission});
  }

  @override
  String getRemotePath() {
    return UTEPedConst.pathDeviceOptions;
  }

  @override
  void initState() {
    // TODO: implement initState
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
  }
}
